<script setup>
import { ref, onMounted, reactive, watch } from "vue";
import userControl from "../../apis/userControl.js";
import { ElNotification } from "element-plus";
import Filter from "../../components/filter.vue";
import elderlyColumns from "../../utils/elderlyColunms.js";
import { useRouter } from "vue-router";
import * as XLSX from "xlsx";
const router = useRouter();

// Dialog visibility state
const dialogFormVisible = ref(false);

// 查询条件
const option = reactive({
  query: "",
  searchType: "",
});

// 监视 option.query，如果为空则查询所有数据
watch(
  () => option.query,
  (newQuery) => {
    if (!newQuery.trim()) {
      // 如果 query 为空
      fetchData({ query: "", searchType: "" }); // 查询所有数据
    }
  }
);

const handleSearchOptions = (options) => {
  option.query = options.query;
  option.searchType = options.searchType;
  fetchData(option); // 传递查询条件进行查询
};

const tableData = ref(null);
const fetchData = async (res) => {
  try {
    const result = await userControl.search(res);
    tableData.value = result;
  } catch (error) {
    ElNotification({
      title: "错误",
      message: error.message || "操作失败",
      type: "error",
    });
  }
};

// Form data
const form = ref({
  elderlyName: "",
  elderlyId: "",
  gender: "",
  contactNumber: "",
  familyContactNumber: "",
  residence: "",
  location: "",
});

// Form submission handler
const addElderly = async () => {
  try {
    const payload = { ...form.value };
    console.log(form.value);
    await userControl.addElderly(payload);
    dialogFormVisible.value = false;

    ElNotification({
      title: "成功",
      message: "注册成功",
      type: "success",
    });
  } catch (error) {
    ElNotification({
      title: "错误",
      message: error.message || "操作失败",
      type: "error",
    });
  }
};

// Handle dialog opening
const openDialog = () => {
  dialogFormVisible.value = true;
};

// 初始加载时查询数据
onMounted(() => {
  fetchData(option);
});
const handleRowClick = (row) => {
  const userId = row.elderlyId;

  router.push({
    name: "person",
    state: { userId },
  });
};
//下载excel模板
const downloadTemplate = () => {
  const link = document.createElement("a");
  link.href = "/template.xlsx";
  link.download = "template.xlsx";
  link.click();
};
//处理文件上传
const handleFileUpload = async (e) => {
  const file = e.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (event) => {
      const data = new Uint8Array(event.target.result);
      const workbook = XLSX.read(data, { type: "array" });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet);

      // 调用后端接口进行用户注册
      registerUsers(jsonData);
    };
    reader.readAsArrayBuffer(file);
  }
};
// 注册用户
const registerUsers = async (users) => {
  try {
    const response = await userControl.registerUsers(users);
    console.log(response.data);
  } catch (error) {
    console.error("注册失败:", error);
  }
};
</script>

<template>
  <el-tabs type="border-card">
    <el-tab-pane label="注册">
      <div>
        <button @click="downloadTemplate">下载 Excel 模板</button>
        <input type="file" @change="handleFileUpload" accept=".xlsx,.xls" />
      </div>
      <div>
        <Filter @sendSearchOptions="handleSearchOptions" />
      </div>
      <!-- Animated Plus Icon -->
      <div class="icon-container" @click="openDialog">
        <el-icon class="plus-icon">
          <Plus />
        </el-icon>
      </div>
    </el-tab-pane>
    <el-tab-pane label="查询">
      <div>
        <Filter @sendSearchOptions="handleSearchOptions" />
      </div>
      <div>
        <el-table
          :data="tableData"
          style="width: 100%"
          border
          @row-click="handleRowClick"
        >
          <el-table-column
            v-for="(column, index) in elderlyColumns"
            :label="column.label"
            :key="index"
            :prop="column.props"
            :min-width="column.minWidth || 120"
            :fixed="column.fixed || null"
            :formatter="column.formatter"
          ></el-table-column>
        </el-table>
      </div>
    </el-tab-pane>
  </el-tabs>

  <!-- Registration Form Dialog -->
  <el-dialog
    v-model="dialogFormVisible"
    title="注册表"
    width="600px"
    class="custom-dialog"
  >
    <el-form :model="form" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" required>
            <el-input v-model="form.elderlyName" autocomplete="off" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="老人ID" required>
            <el-input v-model="form.elderlyId" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" required>
            <el-select v-model="form.gender" placeholder="请选择性别">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" required>
            <el-input v-model="form.contactNumber" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="家属电话" required>
            <el-input v-model="form.familyContactNumber" autocomplete="off" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="家庭住址">
            <el-input v-model="form.residence" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="社区编号">
        <el-input v-model="form.location" autocomplete="off" />
      </el-form-item>
    </el-form>

    <!-- Dialog Footer -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">撤回</el-button>
        <el-button type="primary" @click="addElderly">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
/* Plus Icon Container */
.icon-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #f5f7fa;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.plus-icon {
  font-size: 28px;
  color: #409eff;
  transition: transform 0.3s ease, color 0.3s ease;
}

/* Hover Effect */
.icon-container:hover {
  background-color: #e6f7ff;
  transform: scale(1.1);
}

.icon-container:hover .plus-icon {
  color: #66b1ff;
}

/* Click Effect */
.icon-container:active {
  transform: scale(0.9);
}

/* Custom Dialog */
.custom-dialog .el-dialog {
  border-radius: 10px;
  padding: 20px;
}

/* Dialog Footer Alignment */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* Form Field Styling */
.el-input,
.el-select {
  height: 40px;
}
</style>
